<?php

namespace yiike\company\backend\controllers;
use yiike\company\model\TtycToker;
use yiike\company\model\TtycTokerSearch;
use dmstr\bootstrap\Tabs;
use yii\web\HttpException;
use yii\helpers\Url;
use yii\filters\AccessControl;
use common\models\Region;
/**
* This is the class for controller "TtycTokerController".
*/
class TtycTokerController extends \yiike\company\backend\controllers\base\TtycTokerController
{
    var $authkey = 'e3e0e1f5';
    //推客
    public function actionIndex()
    {
        $_GET['TtycTokerSearch']['company_id'] = \Yii::$app->user->identity->id;
        $_GET['TtycTokerSearch']['type'] = 2;
        $searchModel  = new TtycTokerSearch;
        $dataProvider = $searchModel->search($_GET);

        Tabs::clearLocalStorage();

        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
    //商圈
    public function actionCommunity()
    {
        $_GET['TtycTokerSearch']['company_id'] = \Yii::$app->user->identity->id;
        $_GET['TtycTokerSearch']['type'] = 1;
        $searchModel  = new TtycTokerSearch;
        $dataProvider = $searchModel->search($_GET);

        Tabs::clearLocalStorage();

        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->render('community_index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
    //添加商圈
    public function actionCreate()
    {
        $model = new TtycToker;

        try {
            if ($model->load($_POST)) {

                $mobile = $_POST['TtycToker']['phone'];
                $userpass = trim($_POST['TtycToker']['userPass']);
                if (empty($userpass) || strlen($userpass) < 6) {
                    \Yii::$app->getSession()->setFlash('error', '密码格式不正确, 长度最少6位!');
                }
                $salt = $this->random(8);
                $mobile_user = (new \yii\db\Query())
                    ->select(['uid'])
                    ->from('ims_mc_members')
                    ->where(['mobile' => $mobile])
                    ->all();

                if ($mobile_user) {
                    \Yii::$app->getSession()->setFlash('error', '码已存在！');
                }
                $password = md5($userpass . $salt . $this->authkey);
                $timeStamp = time();
                $data = [
                    'uniacid' => 2,
                    'salt' => $salt,
                    'groupid' => 2,
                    'mobile' => $mobile,
                    'createtime' => $timeStamp,
                    'password' => $password
                ];

                $res = \Yii::$app->getDb()->createCommand()->insert('ims_mc_members', $data)->execute();
                $insert_id = \Yii::$app->getDb()->getLastInsertID();

                $province = $_POST['TtycToker']['province'];

                $province = Region::getCityName($province);
                $city = $_POST['TtycToker']['city'];
                $city = Region::getCityName($city);
                $district = $_POST['TtycToker']['district'];
                $district = Region::getCityName($district);

                $model->location_p = $province;
                $model->location_c = $city;
                $model->location_a = $district;
                $model->uid = $insert_id;
                $model->company_id = \Yii::$app->user->identity->id;
                if ($model->save()) {
                    return $this->redirect(['view', 'id' => $model->id]);
                }

            } elseif (!\Yii::$app->request->isPost) {
                $model->load($_GET);
            }
        } catch (\Exception $e) {
            $msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage();
            $model->addError('_exception', $msg);
        }
        return $this->render('create', ['model' => $model]);
    }
    //修改商圈
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->province = Region::getCityId($model->location_p);
        $model->city = Region::getCity($model->location_c,$model->province);
        $model->district = Region::getCity($model->location_a,$model->city);
        if($model->load($_POST)){

            $province = $_POST['TtycToker']['province'];
            $province = Region::getCityName($province);
            $city = $_POST['TtycToker']['city'];
            $city = Region::getCityName($city);
            $district = $_POST['TtycToker']['district'];
            $district = Region::getCityName($district);
            $model->location_p = $province;
            $model->location_c = $city;
            $model->location_a = $district;
            if ($model->save()) {
                return $this->redirect(Url::previous());
            }
        }

        else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    //修改推客
    public function actionUpdateToker($id)
    {
        $model = $this->findModel($id);
        $company_id = \Yii::$app->user->identity->id;
        $communities = TtycToker::find()->where(['type'=>1,'company_id'=>$company_id])->all();

        $model->province = Region::getCityId($model->location_p);
        $model->city = Region::getCity($model->location_c,$model->province);
        $model->district = Region::getCity($model->location_a,$model->city);
        if($model->load($_POST)){

            $province = $_POST['TtycToker']['province'];
            $province = Region::getCityName($province);
            $city = $_POST['TtycToker']['city'];
            $city = Region::getCityName($city);
            $district = $_POST['TtycToker']['district'];
            $district = Region::getCityName($district);
            $model->location_p = $province;
            $model->location_c = $city;
            $model->location_a = $district;
            if ($model->save()) {
                return $this->redirect(Url::previous());
            }
        } else {
            return $this->render('toker_update', [
                'model' => $model,
                'communities' => $communities,
            ]);
        }
    }
    //详情
    public function actionView($id,$type)
    {

        \Yii::$app->session['__crudReturnUrl'] = Url::previous();
        Url::remember();
        Tabs::rememberActiveState();
        $model = $this->findModel($id);
        if($type=='toker'){
            $model->type='toker';
        }else{
            $model->type='community';
        }
        return $this->render('view', [
            'model' => $model,
        ]);
    }
    public function actionDelete($id)
    {
        try {

            $this->findModel($id)->delete();
        } catch (\Exception $e) {
            $msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage();
            \Yii::$app->getSession()->addFlash('error', $msg);
            return $this->redirect(Url::previous());
        }

// TODO: improve detection
        $isPivot = strstr('$id',',');
        if ($isPivot == true) {
            return $this->redirect(Url::previous());
        } elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
            Url::remember(null);
            $url = \Yii::$app->session['__crudReturnUrl'];
            \Yii::$app->session['__crudReturnUrl'] = null;

            return $this->redirect($url);
        } else {
            return $this->redirect(['index']);
        }
    }
    //省市县三级
    public function actions()
    {
        $actions=parent::actions();
        $actions['get-region']=[
            'class'=>\chenkby\region\RegionAction::className(),
            'model'=>\common\models\Region::className()
        ];
        return $actions;
    }
    //生成随机数
    public function random($length, $numeric = FALSE)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }
}
